import { Col, Icon, Rate, Row, Spin } from "antd";
import { Card, ListView, SearchBar, Tabs, WhiteSpace } from "antd-mobile";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { getWebViewRetObjectType, request, setMainFormTitle, subscribeWebViewNotify } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/app/util-tool";
import './index.less';
const tabs = [
    { title: '距离' },
    { title: '活动数' },
    { title: '报名数' },
    { title: '关注度' },
];
function MyBody(props: any) {
    return (
        <div className="am-list-body my-body" style={{ height: '100%' }}>
            {props.children}
        </div>
    );
}
/**
 * 组件：幸福院列表视图控件状态
 */
export interface HappinessHomeListViewState extends ReactViewState {

    /** 长列表数据 */
    dataSource?: any;
    /** 请求的数据 */
    list?: any[];
    /** 上拉加载 */
    upLoading?: boolean;
    /** 下拉刷新 */
    pullLoading?: boolean;
    /** 长列表容器高度 */
    height?: any;
    // 当前的tab
    tab?: any;
    location?: any;

    empty: any;
    animating: any;
    pageCount: number;
    page?: number;
    keyword?: string;
}
/**
 * 组件：幸福院列表视图控件
 */
export class HappinessHomeListView extends ReactView<HappinessHomeListViewControl, HappinessHomeListViewState> {
    first_in: boolean;

    constructor(props: any) {
        super(props);
        this.first_in = true;
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            dataSource: ds,
            upLoading: false,
            pullLoading: false,
            height: document.documentElement!.clientHeight,
            tab: tabs[0]['title'],
            location: undefined,
            list: [],
            empty: false,
            animating: true,
            pageCount: 10,
            page: 1,
            keyword: "",
        };
    }
    componentDidMount() {
        setMainFormTitle('社区幸福院');
        const messageCb = (e: any) => {
            const retObject = JSON.parse(e.data);
            if (getWebViewRetObjectType(retObject) === 'getPhonePosition') {
                const location = retObject.data;
                if (location === undefined) {
                    // Toast.fail('获取位置信息失败');
                }
                this.setState(
                    {
                        location: retObject.data
                    },
                    () => {
                        this.getHappinessListData(tabs[0]['title']);
                    }
                );
            }
        };

        if ((window as any).ReactNativeWebView) {
            subscribeWebViewNotify(messageCb);
        } else {
            this.getHappinessListData(tabs[0]['title']);
        }
        this.getPhonePosition();
    }

    getPhonePosition() {
        // Toast.info('认证成功：' + e.data);
        if ((window as any).ReactNativeWebView) {
            (window as any).ReactNativeWebView.postMessage(
                JSON.stringify({
                    function: 'getPhonePosition',
                    params: undefined
                })
            );
        }
    }
    getHappinessListData(type: string = '', newPage: number = 1) {
        let { list, location, pageCount, keyword } = this.state;
        let param: any = { personnel_category: '幸福院' };
        if (type !== '') {
            if (type === '距离') {
                param['sortByDistance'] = true;
            } else {
                param['sort'] = type;
            }
        }
        if (keyword !== '') {
            param['name'] = keyword;
        }
        param = { ...param, ...location };
        this.setState(
            {
                animating: true,
            },
            () => {
                // 获取幸福院信息
                request(this, AppServiceUtility.person_org_manage_service.get_all_organization_list!(param, newPage, pageCount))
                    .then((data: any) => {
                        if (data && data.result.length > 0) {
                            this.setState({
                                list: list!.concat(data.result),
                                animating: false,
                                page: newPage,
                            });
                        } else {
                            this.setState({
                                animating: false,
                                empty: true,
                            });
                        }
                    })
                    .catch(error => {
                        console.error(error);
                    });
            }
        );
    }
    toInfo(id: string) {
        this.props!.history!.push(ROUTE_PATH.happinessHomeInfo + '/' + id);
    }
    tabClick(e: any) {
        this.setState(
            {
                tab: e['title'],
                list: [],
                empty: false,
            },
            () => {
                this.getHappinessListData(e['title'] || '');
            }
        );
    }
    searchKey(e: any) {
        this.setState(
            {
                keyword: e,
                empty: false,
                list: [],
            },
            () => {
                this.getHappinessListData(this.state.tab);
            }
        );
    }
    /** 下拉事件 */
    onEndReached = () => {
        const { animating, page, tab } = this.state;
        if (animating === true) {
            return;
        }
        this.getHappinessListData(tab, page! + 1);
    }
    render() {
        const { list, dataSource, animating, empty } = this.state;
        // 获取item进行展示
        const renderRow = (owData: any, sectionID: any, rowID: any) => {
            return (
                <Card className='list-conten'>
                    <Row type='flex' justify='center' onClick={() => this.toInfo(owData.id)}>
                        <Col className='list-col' span={10}><img src={owData.organization_info.picture_list && owData.organization_info.picture_list.length > 0 ? owData.organization_info.picture_list[0] : ''} style={{ height: '100%', width: '100%', objectFit: 'cover', display: 'block' }} /></Col>
                        <Col span={14} className='list-col'>
                            <Row><strong>{owData.name}</strong></Row>
                            <Row><Rate allowHalf={true} disabled={true} value={owData['organization_info'] && owData['organization_info']['star_level'] ? Number(owData['organization_info']['star_level']) : 4} /></Row>
                            <Row><span className="font-orange">{owData.activity_count || 0}</span>次活动&nbsp;&nbsp;&nbsp;&nbsp;<span className="font-orange">{owData.participate_count || 0}</span>条报名</Row>
                            <Row>{owData['organization_info'] && owData['organization_info']['telephone'] ? owData['organization_info']['telephone'] : ''}</Row>
                            <Row className="happiness-address" style={{ "WebkitBoxOrient": "vertical" }}>{owData['organization_info'] && owData['organization_info']['address'] ? owData['organization_info']['address'] : ''}</Row>
                            <Row type="flex" justify="space-between">
                                <Col span={12}>{owData.division_name} {owData.distance ? '| ' + owData.distance.toFixed(2) + 'km' : ''}</Col>
                                <Col span={12} style={{ textAlign: 'right' }}>
                                    <span style={{ marginRight: '10px' }}>
                                        <Icon type="heart" theme="filled" style={{ marginRight: '5px' }} />{owData.follow_count}
                                    </span>
                                </Col>
                            </Row>
                        </Col>
                    </Row>
                </Card>
            );
        };
        return (
            <Row>
                <SearchBar placeholder="搜索" maxLength={8} onSubmit={(e: any) => this.searchKey(e)} />
                <Tabs
                    tabs={tabs}
                    initialPage={0}
                    onTabClick={(e) => this.tabClick(e)}
                />
                <div className='tabs-content'>
                    {
                        list && list.length ?
                            <ListView
                                ref={el => this['lv'] = el}
                                dataSource={dataSource.cloneWithRows(list)}
                                renderRow={renderRow}
                                initialListSize={10}
                                pageSize={10}
                                renderBodyComponent={() => <MyBody />}
                                style={{ height: this.state.height }}
                            /> : null
                    }
                    {animating ? <Row>
                        <WhiteSpace size="lg" />
                        <Row style={{ textAlign: 'center' }}>
                            <Spin size="large" />
                        </Row>
                        <WhiteSpace size="lg" />
                    </Row> : null}
                    {empty ? <Row>
                        <WhiteSpace size="lg" />
                        <Row className='tabs-content' type='flex' justify='center'>{list && list.length ? '已经是最后一条了' : '无数据'}</Row>
                        <WhiteSpace size="lg" />
                    </Row> : null}
                </div>
            </Row>
        );
    }
}

/**
 * 组件：幸福院列表视图控件
 * 控制幸福院列表视图控件
 */
@addon('HappinessHomeListView', '幸福院列表视图控件', '控制幸福院列表视图控件')
@reactControl(HappinessHomeListView, true)
export class HappinessHomeListViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}